import os
import pytest
from selenium import webdriver
from bo.page_factory import PageFactory #简单工厂模式调用
from data_file_analysis.yaml_analysis import YamlAnalysis as ya

work_wechat_url = 'https://work.weixin.qq.com/wework_admin/loginpage_wx?from=myhome' #企业微信地址
cur_path = os.path.abspath(os.path.dirname(__file__))  # 获取当前文件目录
root_path = os.path.dirname(cur_path)

# 设置页面cookies
def set_cookies(driver):
    cookies_path = f'{root_path}/bo/cookies.yaml'
    cookies_dict = ya.return_yaml_data(cookies_path, "cookies")
    for cookie in cookies_dict:
        if 'expiry' in cookie.keys():
            cookie.pop("expiry")
        driver.add_cookie(cookie)

def page_fa_init():
    page_factory = PageFactory()
    return page_factory

#chrome浏览器，有界面模式
@pytest.fixture(scope="session")
def chrome_driver():
    print("开始执行")
    driver = webdriver.Chrome()
    driver.get(work_wechat_url)
    set_cookies(driver)
    driver.get(work_wechat_url)
    index = page_fa_init().create_page_object('index', driver)
    yield index
    print("执行结束")
    driver.close()
    driver.quit()

#firefox浏览器，有界面模式
@pytest.fixture(scope="session")
def firefox_driver():
    print("开始执行")
    driver = webdriver.Firefox()
    driver.get(work_wechat_url)
    set_cookies(driver)
    driver.get(work_wechat_url)
    index = page_fa_init().create_page_object('index', driver)
    yield index
    print('执行结束')
    driver.close()
    driver.quit()

#Chrome浏览器复用模式
@pytest.fixture(scope="session")
def chrome_debug_driver():
    print("开始执行")
    option = webdriver.ChromeOptions()
    option.add_experimental_option('w3c',False)
    option.debugger_address = '127.0.0.1:9222'
    driver = webdriver.Chrome(options=option)
    index = page_fa_init().create_page_object('index', driver)
    driver.get(work_wechat_url)
    yield index
    print("执行结束")

#多浏览+无界面模式
@pytest.fixture(scope="session")
def get_driver():
    browser = os.getenv('browser')

    if browser == 'firefox':
        print('启动火狐浏览器')
        option_firefox = webdriver.FirefoxOptions()
        option_firefox.add_argument('--headless')
        driver = webdriver.Firefox(options=option_firefox)

    if browser == 'chrome':
        print('启动谷歌浏览器')
        option_chrome = webdriver.ChromeOptions()
        option_chrome.add_argument('--headless')
        driver = webdriver.Chrome(options=option_chrome)

    driver.get(work_wechat_url)
    set_cookies(driver)
    driver.get(work_wechat_url)
    index = page_fa_init().create_page_object('index', driver)
    yield index
    print('关闭浏览器')
    driver.close()
    driver.quit()